/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Organization.DataLayer;
// Blibliotecas propias
import Utilities.*;
import CommonData.CommonDataManager;
import DataModel.*;
import java.util.*;
import java.sql.ResultSet;
import javax.xml.parsers.*;
import org.w3c.dom.*;

/**
 *
 * @author Carlos
 */
public class OrganizationDataManager
{
    // <editor-fold defaultstate="collapsed" desc="Singleton">
    private static OrganizationDataManager _instance = new OrganizationDataManager();

    private OrganizationDataManager()
    {
    }

    public static OrganizationDataManager GetInstance()
    {
        return _instance;
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="Public Methods">
    public Organization[] GetOrganizations()
    {
        DataAccesor accesor = DataAccesor.GetInstance();
        String spName = Constants.SP_NAME_GET_ORGANIZATIONS;
        SQLParameter[] parameters = new SQLParameter[0];
        try
        {
            ResultSet result = accesor.ExecuteInputSP(spName, parameters);
            StringBuilder sb = new StringBuilder();
            while(result.next())
                sb.append(result.getString(1));
            result.close();
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            org.xml.sax.InputSource inStream = new org.xml.sax.InputSource();
            inStream.setCharacterStream(new java.io.StringReader(Constants.XML_START + sb.toString() + Constants.XML_END));
            Document xmlDoc = docBuilder.parse(inStream);/**/
            // Creamos la organización
            NodeList nodeList = xmlDoc.getElementsByTagName(Constants.XML_ORG_NODE);
            LinkedList<Organization> orgList = new LinkedList<Organization>();
            for(int xmlIndex = 0; xmlIndex < nodeList.getLength(); xmlIndex++)
            {
                Node orgNode = nodeList.item(xmlIndex);
                NamedNodeMap attributes = orgNode.getAttributes();
                int orgId = Integer.parseInt(attributes.getNamedItem(Constants.XML_ORG_NODE_ID).getNodeValue());
                String name = attributes.getNamedItem(Constants.XML_ORG_NODE_NAME).getNodeValue();
                String code = attributes.getNamedItem(Constants.XML_ORG_NODE_CODE).getNodeValue();
                String legalId = attributes.getNamedItem(Constants.XML_ORG_NODE_LEGAL_ID).getNodeValue();
                String address = attributes.getNamedItem(Constants.XML_ORG_NODE_ADDRESS).getNodeValue();
                int countryId = Integer.parseInt(attributes.getNamedItem(Constants.XML_ORG_NODE_COUNTRY_ID).getNodeValue());
                String postBox = attributes.getNamedItem(Constants.XML_ORG_NODE_POST_CODE).getNodeValue();
                NodeList phoneNodes = orgNode.getChildNodes();
                LinkedList<String> phones = new LinkedList<String>();
                for(int phoneIndex = 0; phoneIndex < phoneNodes.getLength(); phoneIndex++)
                    phones.add(phoneNodes.item(phoneIndex).getAttributes().getNamedItem(Constants.XML_ORG_RESP_PHONE_NODE_NUMBER).getNodeValue());
                String[] phoneArr = new String[phones.size()];
                Organization organization = new Organization(name, code, orgId, legalId, address, code, phones.toArray(phoneArr), getOrganizationResponsibles(orgId), CommonDataManager.GetInstance().GetCountry(countryId));
                orgList.add(organization);
            }
            Organization[] orgArr = new Organization[orgList.size()];
            return orgList.toArray(orgArr);
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
            return null;
        }
    }

    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="Private Methods">
    private User[] getOrganizationResponsibles(int orgId)
    {
        DataAccesor accesor = DataAccesor.GetInstance();
        String spName = Constants.SP_NAME_GET_ORG_RESPONSIBLES;
        SQLParameter[] parameters = {new SQLParameter(Constants.SP_PARAM_GET_ORG_RESPONSIBLES_ORG_ID, orgId)};
        try
        {
            ResultSet result = accesor.ExecuteInputSP(spName, parameters);
            StringBuilder sb = new StringBuilder();
            while(result.next())
                sb.append(result.getString(1));
            result.close();
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            org.xml.sax.InputSource inStream = new org.xml.sax.InputSource();
            inStream.setCharacterStream(new java.io.StringReader(Constants.XML_START + sb.toString() + Constants.XML_END));
            Document xmlDoc = docBuilder.parse(inStream);
            // Creamos la organización
            NodeList nodeList = xmlDoc.getElementsByTagName(Constants.XML_ORG_RESP_NODE);
            LinkedList<User> respList = new LinkedList<User>();
            for(int xmlIndex = 0; xmlIndex < nodeList.getLength(); xmlIndex++)
            {
                Node orgNode = nodeList.item(xmlIndex);
                NamedNodeMap attributes = orgNode.getAttributes();
                //public static final String XML_ORG_RESP_PHONE_NODE = "Tel";
                //public static final String XML_ORG_RESP_PHONE_NODE_NUMBER = "NumeroTelefono";
                String name = attributes.getNamedItem(Constants.XML_ORG_RESP_NODE_NAME).getNodeValue();
                String nickname = attributes.getNamedItem(Constants.XML_ORG_RESP_NODE_NICK).getNodeValue();
                int personId = Integer.parseInt(attributes.getNamedItem(Constants.XML_ORG_RESP_NODE_ID).getNodeValue());
                String lastname1 = attributes.getNamedItem(Constants.XML_ORG_RESP_NODE_LAST_NAME_1).getNodeValue();
                String lastname2 = attributes.getNamedItem(Constants.XML_ORG_RESP_NODE_LAST_NAME_2).getNodeValue();
                String email = attributes.getNamedItem(Constants.XML_ORG_RESP_NODE_EMAIL).getNodeValue();
                int countryId = Integer.parseInt(attributes.getNamedItem(Constants.XML_ORG_RESP_NODE_COUNTRY_ID).getNodeValue());
                NodeList phoneNodes = orgNode.getChildNodes();
                LinkedList<String> phones = new LinkedList<String>();
                for(int phoneIndex = 0; phoneIndex < phoneNodes.getLength(); phoneIndex++)
                    phones.add(phoneNodes.item(phoneIndex).getAttributes().getNamedItem(Constants.XML_ORG_RESP_PHONE_NODE_NUMBER).getNodeValue());
                String[] phoneArr = new String[phones.size()];
                respList.add(new User(personId, name, lastname1, lastname2, email, CommonDataManager.GetInstance().GetCountry(countryId), phones.toArray(phoneArr), nickname, User.UserType.ProjectUser));
            }
            User[] userArr = new User[respList.size()];
            return respList.toArray(userArr);
        }
        catch(Exception ex)
        {
            return null;
        }
    }
    // </editor-fold>
}
